const path = require("path");
const fs = require("fs");
const Toolbox = require("../lib/Toolbox")
const StaticFU = require("../lib/StaticFormUploader").StaticFormUploader;
const axios = require("axios").default;

let sfu = new StaticFU;

(async boot => {
  let list = await Toolbox.safeListDir(path.join(__dirname, "../tmp"));
  for (let ol of list) {
    if (ol.stats.isFile()) {
      let o_up = await sfu.upload_udesk(ol.full_path);
      if (o_up.ok) {
        console.log(ol.relative_path);
        let o_mime = await getLinkContentType(o_up.data.link);
        console.log('[',o_mime,']', o_up.data.link);
        console.log('')
      } else {
        console.error(o_up.msg);
      }
    }
  }

});

(async test0822=>{
  let uper = new StaticFU();
  let form = uper._common_form_generator(path.join(__dirname,"./xxxxx.json"),"xxxxxxxxx");
  let writ = fs.createWriteStream(path.join(__dirname,"./form.txt"));
  form.pipe(writ);
  form.on("close",()=>{
    debugger
  })
  
})();

/**
 * @returns {Promise<string>}
 * @param {String} link 
 */
function getLinkContentType(link) {
  return new Promise(resolve => {
    axios({
      url: link,
      method: "get",
      responseType: 'stream'
    }).then(response => {
      if (!(response.status == 200)) {
        return resolve(`HTTP ${response.status} ${response.statusText}`)
      }
      if (!(response.headers && response.headers["content-type"])) {
        return resolve("NO content-type header")
      }
      resolve(response.headers["content-type"]);
    }).catch(axerr => {
      resolve(axerr);
    })
  })

}
